#coding=utf-8
import sys
from tornado.gen import coroutine,Return,sleep
from .model import UserSubscribe,UserInfo,Users,AuthUsers,CellPhoneUsers
from ..error import SerivceError
from .tools import PasswordVerify
import traceback
from datetime import datetime


def get_subscribe_by_user(user_id):
    obj = UserSubscribe.all_objects().filter(uid=user_id).select()
    if obj:
        return obj.feed_id


def add_subscribe(user_id,feed_id):
    obj = UserSubscribe()
    obj.datamap['id'] = user_id
    obj.feed_id = feed_id
    obj.save()
    #UserSubscribe.__class__.insert_nx_update_ex(data=obj.datamap)


def set_userinfo(user_id,data):
    obj = UserInfo.all_objects().filter(user_id).select()
    if obj is None:
        new_obj = UserInfo()
        new_obj.datamap['id'] = user_id
        for key,value in data.items():
            setattr(new_obj,key,value)
        new_obj.save()
    else:
        obj.update_datamap(data)
        obj.save()


def have_userinfo(user_id):
    obj = UserInfo.all_objects().filter(uid=user_id).select()
    if obj is not None:
        return True
    else: 
        return False


def get_user_info(user_id):
    user_obj = AuthUsers.all_objects().filter(user_id).select()
    if not user_obj:
        return None
    else:
        return {'nickname':user_obj.nickname,
                'headimgurl':user_obj.logo,
                'id':user_obj.uid,
                'inited':user_obj.is_inited}


def initialize(user_id):
    AuthUsers.submit('UPDATE neican_auth_user SET is_inited=1 WHERE id=%s',[user_id])


def register_phone(phone_num,password,email):
    phone_user_obj = CellPhoneUsers.all_objects().filter(phone_num=phone_num).select()
    if phone_user_obj:
        return False,'registered'
    # 将整个插入封装入事务
    secert_str = PasswordVerify(password).secert_str
    conn = CellPhoneUsers.write()
    cursor = conn.cursor()
    try:
        conn.begin()
        sql = 'INSERT INTO neican_auth_user (is_superuser,nickname,email,email_pass,is_staff,is_inited,is_active,date_joined) VALUES (0,%s,%s,0,0,0,1,%s)'
        cursor.execute(sql, [phone_num,email,datetime.now()])
        last_id = cursor.lastrowid
        sql = 'INSERT INTO cell_phone_user (phone_num,password,user_id) VALUES (%s,%s,%s)'
        cursor.execute(sql, [phone_num,secert_str,last_id])
        cursor.close()
        conn.commit()
        conn.close()
    except:
        conn.rollback()
        cursor.close()
        conn.close()
        #exc_type, exc_value, _ = sys.exc_info()
        return False,'inner error'
    return True,'success'


def reset_phone_password(phone_num,new_password):
    conn = CellPhoneUsers.write()
    new_secert_str = PasswordVerify(new_password).secert_str
    cursor = conn.cursor()
    try:
        sql = 'UPDATE cell_phone_user SET password=%s WHERE phone_num=%s'
        effect_row = cursor.execute(sql, [new_secert_str,phone_num])
        cursor.close()
        conn.close()
    except:
        cursor.close()
        conn.close()
        #traceback.print_exc()
        return False
    if effect_row == 0:
        return False
    return True


def bind_phone(phone_num,password,user_id):
    phone_user_obj = CellPhoneUsers.all_objects().filter(phone_num=phone_num).select()
    if phone_user_obj:
        return False,'registered'
    new_phone_user_obj = CellPhoneUsers()
    new_phone_user_obj.password=PasswordVerify(password).secert_str
    new_phone_user_obj.user_id = user_id
    new_phone_user_obj.phone_num=phone_num
    new_phone_user_obj._save_create()
    sql,values = new_phone_user_obj._insert_sql(new_phone_user_obj.datamap)
    conn=CellPhoneUsers.write()
    cursor=conn.cursor()
    try:
        conn.begin()
        cursor.execute(sql,values)
        cursor.execute('UPDATE neican_auth_user SET is_active=1 WHERE id=%s',[user_id])
        conn.commit()
        cursor.close()
        conn.close()
    except:
        conn.rollback()
        cursor.close()
        conn.close()
        return False, 'db error'
    return True,'success'


def set_email(user_id,email):
    conn = Users.write()
    cursor = conn.cursor()
    try:
        sql = 'UPDATE neican_auth_user SET email=%s,email_pass=%s WHERE id=%s AND email!=%s'
        effect_row = cursor.execute(sql, [email,0, user_id,email])
        cursor.close()
        conn.close()
    except:
        cursor.close()
        conn.close()
        raise SerivceError('inner error')
    if effect_row == 0:
        return False,'email error'
    return True,'success'


def auth_phone_user(phone_num,password):
    phone_user_obj = CellPhoneUsers.all_objects().filter(phone_num=phone_num).select()
    if phone_user_obj is None:
        return None
    if PasswordVerify(password).verify(phone_user_obj.password):
        sql = 'UPDATE neican_auth_user SET last_login=%s WHERE id=%s'
        AuthUsers.submit(sql,[datetime.now(),phone_user_obj.user_id])
        return phone_user_obj.user_id
    else:
        return None

